<?php
namespace ManiaLivePlugins\MLEPP\Database;

use ManiaLive\Database\Connection;
use ManiaLive\Database\Exception;
use ManiaLive\Utilities\Console;
use ManiaLivePlugins\MLEPP\Database\Structures\multiQuery;

class mleppDatabase {

	public $connection;
	public $type;
	
function __construct($host,$user,$password,$name,$type,$port) {
		try {
				$this->connection = Connection::getConnection($host, $user, $password, $name, $type,$port);
				$this->type = $type;
				Console::printLn('Connection succesfully established !');
		}
		catch (Exception $e)  {
				Console::printLn("Error while connecting:\n".$e->getMessage());
				die();
		}
}
   public function query(multiQuery $query) {
		if(strtolower($this->type) == 'mysql') {
			$go = $query->mysql;
		} else {
			$go = $query->sqlite;
		}

		if(!empty($go)) return $this->connection->query($go);
	}
	
	public function quote($str) {
		return $this->connection->quote($str);	
	}
	
	public function getDatabaseVersion($table, $fromPlugin = null) {
   		$g = new multiQuery();
		$g->mysql =  "SELECT * FROM `databaseversion` WHERE `database_table` = ".$this->quote($table).";";
		$g->sqlite = "SELECT * FROM databaseversion WHERE database_table = ".$this->quote($table).";";
		$query = $this->query($g);

		if($query->recordCount() == 0) {
			return false;
		}
		else {
			$record = $query->fetchStdObject();
			return $record->database_version;
		}
   }
   
   public function setDatabaseVersion($table,$version) {
        $g = new multiQuery();
		$g->mysql =  "SELECT * FROM `databaseversion` WHERE `database_table` = ".$this->quote($table).";";
		$g->sqlite = "SELECT * FROM databaseversion WHERE database_table = ".$this->quote($table).";";
		$query = $this->query($g);

		if($query->recordCount() == 0) {
			$q = new multiQuery();
			$q->mysql = "INSERT INTO `databaseversion` (`database_table`,
								 `database_version`
								 ) VALUES (
								 ".$this->quote($table).",
								 ".$this->quote($version)."
								 )";
			$q->sqlite = "INSERT INTO databaseversion (database_table,
								 database_version
								 ) VALUES (
								 ".$this->quote($table).",
								 ".$this->quote($version)."
								 )";
			$this->query($q);
		} else {
			$q = new multiQuery();
			$q->mysql = "UPDATE
			`databaseversion`
			SET
			`database_version` = ".$this->quote($version)."
			WHERE
			`database_table` = ".$this->quote($table).";";

			$q->sqlite = "UPDATE
			databaseversion
			SET
			database_version = ".$this->quote($version)."
			WHERE
			database_table = ".$this->quote($table).";";
			$this->query($q);
		}
        Console::printLn("set new database version: table $table -> version $version.");
   }
   
   
   
}

?>